package com.lalosoft.misgastos.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.lalosoft.misgastos.config.Constants;
import com.lalosoft.misgastos.domain.Account;
import com.lalosoft.misgastos.domain.Item;
import com.lalosoft.misgastos.service.GastosTarjetaService;

public class GastosTarjetaServiceImpl implements GastosTarjetaService {

	@Override
	public List<Item> getAllItems() {
		
		return null;
	}

	@Override
	public String saveItem(String token, Item item) throws JsonGenerationException, JsonMappingException, IOException, JSONException {
		String result = "";
		String data = saveJsonItem(item);
		URL url = new URL(Constants.SAVE_ITEM + "?token=" + token + "&data=" + data);
		HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
		httpConn.setRequestMethod("GET");
		httpConn.connect();
		if(httpConn.getResponseCode() == 200){
			InputStream inputStream = httpConn.getInputStream();
			// Parse it line by line
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(inputStream));
			StringBuffer sb = new StringBuffer();
			String str = "";
			while ((str = bufferedReader.readLine()) != null) {
				sb.append(str);
			}
			JSONObject json = new JSONObject(sb.toString());
			result = json.getString("itemId");
		} else {
			Log.e("GastosService", "Error en saveItem: " + httpConn.getResponseMessage());
		}
		return result;
	}
	
	private String saveJsonItem(Item aItem){
		JSONObject itemJson = new JSONObject();
		try {
			itemJson.put("detalle", aItem.getDetalle());
			itemJson.put("cantidadCuotas", String.valueOf(aItem.getCantidadCuotas()));
			itemJson.put("fechaCompra", aItem.getFechaCompra());
			itemJson.put("valorCuota", String.valueOf(aItem.getValorCuota()));
			itemJson.put("cuotasRestantes", String.valueOf(aItem.getCuotasRestantes()));
			itemJson.put("idDB", aItem.getIdDB());
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
		
		return itemJson.toString();
	}

	@Override
	public String obtaingData(String token) throws IOException, JSONException {
		String result = "";
		URL url = new URL(Constants.OBTAING_KEY + "?token=" + token);
		HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
		httpConn.setRequestMethod("GET");
		httpConn.connect();
		if(httpConn.getResponseCode() == 200){
			InputStream inputStream = httpConn.getInputStream();
			// Parse it line by line
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(inputStream));
			StringBuffer sb = new StringBuffer();
			String str = "";
			while ((str = bufferedReader.readLine()) != null) {
				sb.append(str);
			}
			result = sb.toString();
		}
		
		return result;
	}

	@Override
	public String saveAccount(Account account) throws IOException, JSONException {
		String token = "";
		URL url = new URL(Constants.SAVE_ACCOUNT + "?username=" + account.getUsername() + "&password=" + account.getPassword() + "&email=" + account.getEmail());
		HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
		httpConn.setRequestMethod("GET");
		httpConn.connect();
		if(httpConn.getResponseCode() == 200){
			InputStream inputStream = httpConn.getInputStream();
			// Parse it line by line
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(inputStream));
			StringBuffer sb = new StringBuffer();
			String str = "";
			while ((str = bufferedReader.readLine()) != null) {
				sb.append(str);
			}
			JSONObject json = new JSONObject(sb.toString());
			String result = json.getString("result");
			if(result.equals("ok")){
				token = json.getString("token");
			} else {
				token = json.getString("cause");
			}
		} else {
			Log.e("GastosService", "Error: " + httpConn.getResponseMessage());
		}
		return token;
	}

	@Override
	public boolean deleteItem(String id) throws IOException, JSONException {
		boolean result = false;
		URL url = new URL(Constants.DELETE_ITEM + "?id=" + id);
		HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
		httpConn.setRequestMethod("GET");
		httpConn.connect();
		if(httpConn.getResponseCode() == 200){
			InputStream inputStream = httpConn.getInputStream();
			// Parse it line by line
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(inputStream));
			StringBuffer sb = new StringBuffer();
			String str = "";
			while ((str = bufferedReader.readLine()) != null) {
				sb.append(str);
			}
			JSONObject json = new JSONObject(sb.toString());
			result = json.getString("result").equals("ok");
		}
		return result;
	}

	@Override
	public String updateAccount(Account account, String token) throws IOException, JSONException {
		String result = "";
		URL url = new URL(Constants.UPDATE_ACCOUNT + "?token=" + token + "&username=" + account.getUsername() + "&password=" + account.getPassword() + "&email=" + account.getEmail());
		HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
		httpConn.setRequestMethod("GET");
		httpConn.connect();
		if(httpConn.getResponseCode() == 200){
			InputStream inputStream = httpConn.getInputStream();
			// Parse it line by line
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(inputStream));
			StringBuffer sb = new StringBuffer();
			String str = "";
			while ((str = bufferedReader.readLine()) != null) {
				sb.append(str);
			}
			JSONObject json = new JSONObject(sb.toString());
			result = json.getString("result");
			if(result.equals("error")){
				result = json.getString("cause");
			}
		}
		return result;
	}

	@Override
	public boolean deleteAllItems(String token) throws IOException, JSONException {
		boolean result = false;
		URL url = new URL(Constants.DELETE_ALL_ITEMS + "?token=" + token);
		HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
		httpConn.setRequestMethod("GET");
		httpConn.connect();
		if(httpConn.getResponseCode() == 200){
			InputStream inputStream = httpConn.getInputStream();
			// Parse it line by line
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(inputStream));
			StringBuffer sb = new StringBuffer();
			String str = "";
			while ((str = bufferedReader.readLine()) != null) {
				sb.append(str);
			}
			JSONObject json = new JSONObject(sb.toString());
			result = json.getString("result").equals("ok");
		}
		return result;
	}

}
